<script setup>
import { Plus, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { getAllBusinesses, addBusiness } from '../api/api'

const list = ref()
const project_inputsRef = ref(null)
const template = () => {
  return { name: '', id: '' }
}
const addNewProjectname = () => {
  if (list.value.length && list.value[0].name.trim() !== '') {
    list.value.unshift(template())
    setTimeout(() => {
      project_inputsRef.value[0]?.focus()
    }, 100)
  }
}
const addNewBusiness = async (name) => {
  const res = await addBusiness({ name })
  if (res.status) return ElMessage.warning(res.msg)
  ElMessage.success('新增驻商单位成功！')
}

onMounted(() => {
  getAllBusinesses()
    .then(async (res) => {
      if (res.status) return ElMessage.warning('获取单位失败！')
      list.value = res.data
    })
    .catch(() => {})
})
</script>
<template>
  <header>驻商单位管理</header>
  <main style="padding: 20px">
    <el-button
      type="primary"
      size="large"
      :icon="Plus"
      style="width: 100%"
      @click="addNewProjectname"
      >添加新驻商单位</el-button
    >
    <div class="work-list-row" v-for="(row, index) in list" :key="index">
      <el-input v-model="row.name" class="work-list-row-ipt" ref="project_inputsRef">
        <template v-if="row.id == ''" #append>
          <el-button :icon="Check" @click="addNewBusiness(row.name)" />
        </template>
      </el-input>
    </div>
  </main>
</template>
<style scoped>
header {
  text-align: center;
  background: #f593af;
  height: 65px;
  color: white;
  position: relative;
  padding-top: 5px;
  font-size: 22px;
  line-height: 55px;
}
.work-list-row {
  border-bottom: 0;
  padding: 0;
}
</style>
